package cn.com.hhrcw.utils;

import lombok.SneakyThrows;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * @author lixingxing
 */
@Component
public class RedisLockUtils {

    private static RedissonClient client;

    @Autowired
    private RedissonClient redissonClient;

    private static final String LOCK_SUFFIX = "_locked";

    @PostConstruct
    public void init() {
        RedisLockUtils.client = redissonClient;
    }

    public static boolean tryLock(String key, int time) {
        return tryLock(key, time, time, TimeUnit.SECONDS);
    }

    public static boolean tryLock(String key, int time, TimeUnit timeUnit) {
        return tryLock(key, time, -1, timeUnit);
    }

    /**
     * 加锁
     * @param key
     * @param time
     * @param waitTime
     * @param timeUnit
     * @return
     */
    @SneakyThrows
    public static boolean tryLock(String key, int time, int waitTime, TimeUnit timeUnit) {
        key += LOCK_SUFFIX;
        RLock lock = client.getLock(key);
        return lock.tryLock(waitTime, time, timeUnit);
    }

    /**
     * 解锁
     * @param key
     */
    public static void unLock(String key) {
        key += LOCK_SUFFIX;
        RLock lock = client.getLock(key);
        if (lock.isLocked() && lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }
}
